//
//  LSHomeViewController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/18.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSHomeViewController.h"
#import "LSHomeDataManager.h"
#import "LSResFirstController.h"
#import "LSTestWrongQuesViewController.h"
#import "AppDelegate.h"
#import "LSResFirstController.h"
#import "KZPronounceImproveVC.h"//音标
#import "KZListenSpeakVocabularyImporveVC.h"//听说词汇
#import "KZUserCenterVC.h"//个人中心
#import "KZUnfamiliarVocabularyImproveVC.h"//错题生词
#import "KZUnfamiliarVocabularyImproveVC_version2.h"
#import "LSHomeLoadingView.h"
#import "BKLineChartView.h"
#import "LSHomeView.h"
#import "LSResFirstController_version2.h"//听力和朗读一级界面

@interface LSHomeViewController ()<UIScrollViewDelegate,UITableViewDelegate>
{
    BKBaseRequest *net;
    UIImageView *_loadingImageView;
    UILabel *_infoLabel;
    LSCircleBtn *_tipBtn;
    NSInteger _count;
    UIImageView *_loadingFullScreenView;
}

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UIImageView *navView ;
@property (nonatomic,assign) CGFloat newy;
@property (nonatomic,assign) CGFloat oldy;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,copy) NSString *weekID;
@property (nonatomic,assign) BOOL isPushUserCenter;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *loadingBackView;
@property (nonatomic,strong) NSMutableDictionary *dictBefore;

@property (nonatomic,strong) NSMutableArray *radomArr;
@property (nonatomic,strong) NSMutableArray *viewArr;

@end

@implementation LSHomeViewController


- (BOOL)checkPermission{
    
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
                [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    if (granted) {
                        bCanRecord = YES;
                    } else {
                        bCanRecord = NO;
                    }
                }];
            }
        } else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
            // 未授权
            [self showSetAlertView];
        } else{
            // 已授权
            NSLog(@"已授权");
        }
    }
    return bCanRecord;
}

//提示用户进行麦克风使用授权
- (void)showSetAlertView {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"麦克风权限未开启" message:@"麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //跳入当前App设置界面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:setAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
    
    
};

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self checkPermission];

    _newy = 0;
    _oldy = 0;
    _dictBefore = [NSMutableDictionary dictionary];
    _radomArr = [NSMutableArray arrayWithArray:@[@0,@1,@2]];
    _viewArr = [NSMutableArray array];

    [self addBYItemviews:@[@"LS-头像"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeRight];
    
    //头部样式背景
    UIImageView *navView =  [[UIImageView alloc] init];
    navView.userInteractionEnabled = YES;
    self.navView = navView;
    navView.image = [UIImage imageNamed:@"LS-蓝色背景"];
    [self.view addSubview:navView];
    navView.backgroundColor = [UIColor blueColor];
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(190-64+kNavgationBar);
    }];
    
    //标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT(13);
    NSString *titleText = @"高考英语听说学习训练平台\n听说智能训练";
    NSRange range = [titleText rangeOfString:@"听说智能训练"];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:titleText];
    [attr addAttributes:@{NSFontAttributeName:FONT(19),NSForegroundColorAttributeName:[UIColor whiteColor]} range:range];
    titleLabel.attributedText = attr;
    [navView addSubview:titleLabel];
    CGFloat top = 20;
    if (isPhoneX) {
        top = 44;
    }
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(navView).offset(top);
        make.centerX.equalTo(navView);
        make.size.mas_equalTo(CGSizeMake(160, 40));
    }];
    
    //白色圆角背景
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    [navView addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(navView);
        make.centerX.equalTo(navView);
        make.size.mas_equalTo(CGSizeMake(kWidth, 45));
    }];
    [backView addRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadii:CGSizeMake(22.5, 22.5) viewRect:CGRectMake(0, 0, kWidth, 45)];
    
    //提示信息
    UILabel *infoLabel = [[UILabel alloc] init];
    _infoLabel = infoLabel;
    [navView addSubview:infoLabel];
    infoLabel.text = @"正在分析您的听说能力，并智能推荐听说训练方式!";
    infoLabel.textColor = [UIColor colorWithHex:0x6ccff6];
    //infoLabel.textColor = [UIColor colorWithHex:0x666666];
    infoLabel.font = [UIFont systemFontOfSize:13*ScalesW];//FONT(13*ScalesW);
    CGSize size = [infoLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13*ScalesW]}];
    [infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(navView).offset(-12.5);
       // make.centerX.equalTo(navView);
        make.size.mas_equalTo(CGSizeMake(size.width+1, 13));
        make.left.equalTo(navView).offset(20);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [infoLabel addGestureRecognizer:tap];
    [infoLabel.layer addAnimation:[self opacityForever_Animation:0.7] forKey:nil];
        
    LSCircleBtn *tipBtn = [[LSCircleBtn alloc] init];
    _tipBtn = tipBtn;
    tipBtn.alpha = 0;
    [navView addSubview:tipBtn];
    [tipBtn setImage:[UIImage imageNamed:@"LS-刷新"] forState:UIControlStateNormal];
    [tipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(infoLabel.mas_right).offset(2);
        make.centerY.equalTo(infoLabel);
        make.size.mas_equalTo(CGSizeMake(15*ScalesW, 15*ScalesW));
    }];
    [tipBtn addTarget:self action:@selector(tapAction) forControlEvents:UIControlEventTouchUpInside];
    
    _tipBtn.userInteractionEnabled = NO;
    _infoLabel.userInteractionEnabled = NO;
    
    //头部gif
    NSMutableArray *images = [NSMutableArray array];
    for (NSInteger i = 0; i<49; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"haha_000%02ld",i]];
        [images addObject:image];
    }
    _loadingImageView = [[UIImageView alloc] init];//WithFrame:CGRectMake((kWidth-60)/2,(ScalesH * 260-60)/2 , 60, 60)];
    [navView addSubview:_loadingImageView];
    [_loadingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
       // make.left.right.equalTo(navView);
        make.top.equalTo(navView).offset(kNavgationBar);
        make.bottom.equalTo(infoLabel.mas_top);
        make.width.mas_equalTo(375);
        make.centerX.equalTo(navView);
    }];
    
    //图表TableView
    [self setupTabelView];
    
    //加载动画1
//    _loadingImageView.animationImages = images;
//    _loadingImageView.animationDuration = 2;
//    _loadingImageView.animationRepeatCount = 0;
//    [_loadingImageView startAnimating];
//    _loadingImageView.image = [UIImage imageNamed:@"haha_00048"];
    
    //加载动画2
    for(NSInteger i = 0 ; i < 3 ; i++) {
        LSHomeLoadingView *loadingView = [[LSHomeLoadingView alloc] initWithFrame:CGRectMake(0,i*160*ScalesH,kWidth, 160*ScalesH)];
        loadingView.index = i;
        loadingView.tag = 9000+i;
        loadingView.userInteractionEnabled = NO;
        [self.tableView addSubview:loadingView];
        [_viewArr addObject:loadingView];
    }
    
    //加载动画
    _loadingFullScreenView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [_loadingFullScreenView gif:@"LS-加载"];
    [self.view addSubview:_loadingFullScreenView];
    //数据调用
    [self loadData];
    
}

- (void)setupTabelView {
    //图表
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;

    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            make.top.equalTo( self.navView.mas_bottom);
        } else {
            make.top.equalTo( self.navView.mas_bottom);
            make.bottom.equalTo(self.view);
        }
    }];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)removeHomeChartView {
    for (NSInteger i = 0; i<3; i++) {
        LSHomeView *homeView = [self.tableView viewWithTag:5000+i];
        [homeView removeFromSuperview];
        homeView = nil;
    }
}

- (void)setupSingleHomeChartView:(NSInteger)i {
    self.tableView.contentSize = CGSizeMake(0, 3 * ScalesH * 260);
    
    NSArray *AbiClassArray = @[@"A",@"B",@"C"];
 
    LSHomeView *homeView = [[LSHomeView alloc] initWithFrame:CGRectMake(0,ScalesH * 260 * i, kWidth, ScalesH * 260)];
    homeView.tag = 5000+i;
    [self.tableView addSubview:homeView];
    
    homeView.index = i;
    
    NSString *AbiClass = AbiClassArray[i];
    NSInteger count = 0;
    for(LSweak *modelweak in self.dataArray) {
        if ([modelweak.AbiClass isEqualToString:AbiClass]) {
            homeView.weakModel = modelweak;
            count++;
            NSString *json = [modelweak yy_modelToJSONString];
            [self.dictBefore setObject:json forKey:AbiClass];
        }
    }
    if (count==0) {
        homeView.weakModel = nil;
    }
    
    
    WeakObj(self);
    homeView.pushBlock = ^(NSString *text) {
        
        if ([text isEqualToString:@"听力能力强化训练"]) {
            
//            LSResFirstController *listen =[[LSResFirstController alloc] init];
            LSResFirstController_version2 *listen = [LSResFirstController_version2 new];
            listen.TypeID = @"SE";
            LSweak *weakModel = self.dataArray[0];
            listen.UpdateTime = weakModel.UpdateTime;
            [selfWeak push:listen];
            
            selfWeak.weekID = @"A1";
            
        } else if ([text isEqualToString:@"错题生词强化训练"]) {
            
            KZUnfamiliarVocabularyImproveVC_version2 *vc = [[KZUnfamiliarVocabularyImproveVC_version2 alloc] init];
            [selfWeak push:vc];
            
            if (homeView.tag==5000) {
                selfWeak.weekID = @"A2";
            } else if (homeView.tag==5001) {
                selfWeak.weekID = @"B3";
            }
            
        } else if ([text isEqualToString:@"听说词汇强化训练"]) {
            
            KZListenSpeakVocabularyImporveVC *vc = [[KZListenSpeakVocabularyImporveVC alloc] init];
            [selfWeak push:vc];
            
            selfWeak.weekID = @"C1";
            
        } else if ([text isEqualToString:@"标准发音强化训练"]) {
            
            KZPronounceImproveVC *vc = [[KZPronounceImproveVC alloc] init];
            [selfWeak push:vc];
            
            selfWeak.weekID = @"B1";
            
        } else if ([text isEqualToString:@"朗读能力强化训练"]) {
            
//            LSResFirstController *read =[[LSResFirstController alloc] init];
            LSResFirstController_version2 *read = [LSResFirstController_version2 new];
            read.TypeID = @"Spn";
            LSweak *weakModel = self.dataArray[0];
            if (self.dataArray.count>1) {
                weakModel = self.dataArray[1];
            }
            read.UpdateTime = weakModel.UpdateTime;
            [selfWeak push:read];
            
            selfWeak.weekID = @"B2";
        }
        
        selfWeak.isPushUserCenter = NO;
    };
    
    
}

- (void)setupHomeChartView {
    self.tableView.contentSize = CGSizeMake(0, 3 * ScalesH * 260);
    
    NSArray *AbiClassArray = @[@"A",@"B",@"C"];
    for (NSInteger i = 0; i<3; i++) {
        LSHomeView *homeView = [[LSHomeView alloc] initWithFrame:CGRectMake(0,ScalesH * 260 * i, kWidth, ScalesH * 260)];
        homeView.tag = 5000+i;
        [self.tableView addSubview:homeView];
        
        homeView.index = i;

        NSString *AbiClass = AbiClassArray[i];
        NSInteger count = 0;
        for(LSweak *modelweak in self.dataArray) {
            if ([modelweak.AbiClass isEqualToString:AbiClass]) {
                homeView.weakModel = modelweak;
                count++;
                NSString *json = [modelweak yy_modelToJSONString];
                [self.dictBefore setObject:json forKey:AbiClass];
            }
        }
        if (count==0) {
            homeView.weakModel = nil;
        }
        
        
        WeakObj(self);
        homeView.pushBlock = ^(NSString *text) {
            
            if ([text isEqualToString:@"听力能力强化训练"]) {
                
                LSResFirstController *listen =[[LSResFirstController alloc] init];
                listen.TypeID = @"SE";
                LSweak *weakModel = self.dataArray[0];
                listen.UpdateTime = weakModel.UpdateTime;
                [selfWeak push:listen];
                
                selfWeak.weekID = @"A1";

            } else if ([text isEqualToString:@"错题生词强化训练"]) {
                
                KZUnfamiliarVocabularyImproveVC_version2 *vc = [[KZUnfamiliarVocabularyImproveVC_version2 alloc] init];
                [selfWeak push:vc];
                
                if (homeView.tag==5000) {
                    selfWeak.weekID = @"A2";
                } else if (homeView.tag==5001) {
                    selfWeak.weekID = @"B3";
                }
                
            } else if ([text isEqualToString:@"听说词汇强化训练"]) {
                
                KZListenSpeakVocabularyImporveVC *vc = [[KZListenSpeakVocabularyImporveVC alloc] init];
                [selfWeak push:vc];
                
                selfWeak.weekID = @"C1";
                
            } else if ([text isEqualToString:@"标准发音强化训练"]) {
                
                KZPronounceImproveVC *vc = [[KZPronounceImproveVC alloc] init];
                [selfWeak push:vc];
                
                selfWeak.weekID = @"B1";
                
            } else if ([text isEqualToString:@"朗读能力强化训练"]) {
                
                LSResFirstController *read =[[LSResFirstController alloc] init];
                read.TypeID = @"Spn";
                LSweak *weakModel = self.dataArray[0];
                if (self.dataArray.count>1) {
                    weakModel = self.dataArray[1];
                }
                read.UpdateTime = weakModel.UpdateTime;
                [selfWeak push:read];
                
                selfWeak.weekID = @"B2";
            }
            
            selfWeak.isPushUserCenter = NO;
        };
       
    }
}

- (UIView *)loadingBackView {
    if (!_loadingBackView) {
        _loadingBackView = [[UIView alloc] init];
        for(NSInteger i = 0 ; i < 3 ; i++) {
            LSHomeLoadingView *loadingView = [[LSHomeLoadingView alloc] initWithFrame:CGRectMake(0,i*160*ScalesH,kWidth, 160*ScalesH)];
            loadingView.index = i;
            loadingView.userInteractionEnabled = NO;
            [_loadingBackView addSubview:loadingView];
        }
    }
    
    return _loadingBackView;
}

#pragma mark === 永久闪烁的动画 ======
-(CABasicAnimation *)opacityForever_Animation:(float)time
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];//必须写opacity才行。
    animation.fromValue = [NSNumber numberWithFloat:1.0f];
    animation.toValue = [NSNumber numberWithFloat:0.1f];//这是透明度。
    animation.autoreverses = YES;
    animation.duration = time;
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];///没有的话是均匀的动画。
    return animation;
}


- (void)rightItemsAction:(NSInteger)rightIndex {
    if (rightIndex==0) {
        KZUserCenterVC *vc = [[KZUserCenterVC alloc] init];
        [self push:vc];
        self.isPushUserCenter = YES;
    }
}


- (void)tapAction {
   
    _count = 0;
    [self.dataArray removeAllObjects];
    [self removeHomeChartView];
    
    _tipBtn.userInteractionEnabled = NO;
    _tipBtn.alpha = 0;
    
    _infoLabel.userInteractionEnabled = NO;
    _infoLabel.text = @"正在分析您的听说能力，并智能推荐听说训练方式!";
    _infoLabel.textColor = [UIColor colorWithHex:0x6ccff6];
    CGSize size = [_infoLabel.text sizeWithAttributes:@{NSFontAttributeName:FONT(13*ScalesW)}];
    [_infoLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(size.width+1, 13));
    }];
    [_infoLabel.layer addAnimation:[self opacityForever_Animation:0.7] forKey:nil];
    
   //动画1
    [_loadingImageView startAnimating];
    
   //动画2
    [_viewArr removeAllObjects];
    _radomArr = [NSMutableArray arrayWithArray:@[@0,@1,@2]];
    for(NSInteger i = 0 ; i < 3 ; i++) {
        LSHomeLoadingView *loadingView = [[LSHomeLoadingView alloc] initWithFrame:CGRectMake(0,i*160*ScalesH,kWidth, 160*ScalesH)];
        loadingView.index = i;
        loadingView.tag = 9000+i;
        loadingView.userInteractionEnabled = NO;
        [self.tableView addSubview:loadingView];
        [_viewArr addObject:loadingView];
    }
    
    self.tableView.contentSize = CGSizeMake(0, 3 * ScalesH * 160);
    
    [self loadData];
}

- (void)getRandom {
 //   int x = arc4random() % _radomArr.count;//取[0,3)随机整数
//   NSNumber *num = _radomArr[x];
    NSNumber *num;
    if (_count==0) {
        num = @0;
        _count ++;
    } else if (_count==1) {
        num = @1;
        _count++;
    } else if (_count==2) {
        num = @2;
        _count++;
    }
    
    NSLog(@"num=%ld",num.integerValue);
    
    LSHomeLoadingView *loadingView = [self.tableView viewWithTag:num.integerValue+9000];
    [loadingView removeFromSuperview];
    loadingView = nil;
 //   [_radomArr removeObject:num];
    
    [self setupSingleHomeChartView:num.integerValue];
    
    self.tableView.contentSize = CGSizeMake(0,self.tableView.contentSize.height-160*ScalesH+260*ScalesH);
    
    [self updateLoadingFrame];

}

- (void)updateLoadingFrame {
    for (NSInteger i = 0; i<3; i++) {
        LSHomeLoadingView *loading = [self.tableView viewWithTag:9000+i];
        LSHomeView *home = [self.tableView viewWithTag:5000+i];
        if (loading) {
            
            [_viewArr replaceObjectAtIndex:i withObject:loading];
            UIView *view1 = _viewArr[0];
            view1.y = 0;
            UIView *view2 = _viewArr[1];
            view2.y = view1.y+view1.height;
            UIView *view3 = _viewArr[2];
            view3.y = view2.y+view2.height;
            NSLog(@"\n视图数组%@",_viewArr);

        } else {
            
            [_viewArr replaceObjectAtIndex:i withObject:home];
            UIView *view1 = _viewArr[0];
            view1.y = 0;
            UIView *view2 = _viewArr[1];
            view2.y = view1.y+view1.height;
            UIView *view3 = _viewArr[2];
            view3.y = view2.y+view2.height;
            NSLog(@"\n视图数组%@",_viewArr);
            
        }
    }

}

- (void)loadData {
    
    LSHomeDataManager *manager =  [[LSHomeDataManager alloc] init];
    NSDictionary *dict = @{
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"XH":DR_UserInfo.UserID,
                           @"HTestID":KGetUserDefaults(@"TestLayer"),
                           @"SubjectID":@"S2-English"
                          };
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    self.dataArray = [NSMutableArray array];
    
    double delayInSeconds = 6.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //执行事件
        
        WeakObj(self);
        [manager requestWithCompltionSuccess:^(LSModelHome *model) {
            
            [selfWeak.dataArray addObjectsFromArray:model.InfoList.firstObject.WeakList];

            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.0 *NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //执行事件
                [selfWeak getRandom];
                
                dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, 0.4 *NSEC_PER_SEC);
                dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
                    //执行事件
                    [selfWeak getRandom];
                     dispatch_time_t popTime3 = dispatch_time(DISPATCH_TIME_NOW, 0.4 *NSEC_PER_SEC);
                    dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){
                        //执行事件
                        [selfWeak getRandom];

                        _tipBtn.userInteractionEnabled = YES;
                        _tipBtn.alpha = 1;
                        _infoLabel.userInteractionEnabled = YES;
                        _infoLabel.text = @"您的听说能力分析如下";
                        _infoLabel.textColor = [UIColor colorWithHex:0x666666];
                        CGSize size = [_infoLabel.text sizeWithAttributes:@{NSFontAttributeName:FONT(13*ScalesW)}];
                        [_infoLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.size.mas_equalTo(CGSizeMake(size.width+1, 13));
                        }];
                        [_infoLabel.layer removeAllAnimations];
                        [_loadingImageView stopAnimating];
                        [_loadingFullScreenView removeFromSuperview];
                        _loadingFullScreenView = nil;
                    });
                });
                
            });
            
            
        } failuer:^(NSString *error) {
            NSLog(@"%@",error);
        }];
    });
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    // 设置导航栏的默认属性(默认为不透明、黑色状态栏)
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];

//    if (self.weekID && ![self.weekID isEqualToString:@""] && !self.isPushUserCenter) {
//        [self updateData];
//    }
}

- (void)updateData {
    
    LSHomeDataManager *manager = [[LSHomeDataManager alloc] init];
    NSDictionary *dict = @{
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"XH":DR_UserInfo.UserID,
                           @"HTestID":KGetUserDefaults(@"TestLayer"),
                           @"SubjectID":@"S2-English",
                           @"WeakID":self.weekID?self.weekID:@""
                           };
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    WeakObj(self);
    [manager updateWithCompltionSuccess:^(LSModelHome *model) {
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:model.InfoList.firstObject.WeakList];
        NSArray *array = model.InfoList.firstObject.WeakList;
        [selfWeak reloadHomeViewWithArray:array];
        
    } failuer:^(NSString *error) {
    
    }];
    
}

- (void)reloadHomeViewWithArray:(NSArray*)array {

    NSArray *AbiClassArray = @[@"A",@"B",@"C"];
    for (NSInteger i = 0; i<3; i++) {
        
        LSHomeView *homeView = [self.tableView viewWithTag:5000+i];
        NSInteger count = 0;
        
        NSString *AbiClass = AbiClassArray[i];
        
        for(LSweak *modelweak in array) {
            if ([modelweak.AbiClass isEqualToString:AbiClass]) {
                count++;
                NSString *json = [modelweak yy_modelToJSONString];
                NSString *jsonBefore = [self.dictBefore objectForKey:AbiClass];
                
                if (![jsonBefore isEqualToString:json]) {
                    
                    [homeView removeFromSuperview];
                    homeView = nil;

                    LSHomeLoadingView *loadingView = [[LSHomeLoadingView alloc] initWithFrame:CGRectMake(0,i*160*ScalesH,kWidth, 160*ScalesH)];
                    loadingView.index = i;
                    loadingView.tag = 9000+i;
                    loadingView.userInteractionEnabled = NO;
                    [self.tableView addSubview:loadingView];
                    [_viewArr replaceObjectAtIndex:i withObject:loadingView];
                    [self updateLoadingFrame];
                    
                    double delayInSeconds = 3.0;
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                        [loadingView removeFromSuperview];
                        [self setupSingleHomeChartView:i];
                        self.tableView.contentSize = CGSizeMake(0,self.tableView.contentSize.height-160*ScalesH+260*ScalesH);
                        [self updateLoadingFrame];
                    });
                }
 
            }
        }
        if (count==0) {//之前没有数据返回后产生数据了
            NSString *jsonBefore = [self.dictBefore objectForKey:AbiClass];
            if (jsonBefore!=nil) {
                [homeView removeFromSuperview];
                homeView = nil;
                
                LSHomeLoadingView *loadingView = [[LSHomeLoadingView alloc] initWithFrame:CGRectMake(0,i*160*ScalesH,kWidth, 160*ScalesH)];
                loadingView.index = i;
                loadingView.tag = 9000+i;
                loadingView.userInteractionEnabled = NO;
                [self.tableView addSubview:loadingView];
                [_viewArr replaceObjectAtIndex:i withObject:loadingView];
                [self updateLoadingFrame];
                
                double delayInSeconds = 2.0;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [loadingView removeFromSuperview];
                    [self setupSingleHomeChartView:i];
                    self.tableView.contentSize = CGSizeMake(0,self.tableView.contentSize.height-160*ScalesH+260*ScalesH);
                    [self updateLoadingFrame];
                });

            }
        }
    }
}

#pragma mark - UISrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    BOOL scrollUporDown = false;
    if ([scrollView isEqual:self.tableView]) {
        NSLog(@"contentOffset=%f",scrollView.contentOffset.y);
        _newy = scrollView.contentOffset.y;
        
        if(_newy>_oldy) {
            scrollUporDown = YES;//朝上
        } else {
            scrollUporDown = NO;//朝下
        }
        _oldy = _newy;
        
        if (scrollUporDown==YES) {
            if (_newy>0) {
                [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(kNavgationBar+40);
                }];
                //添加更新约束动画
                [UIView animateWithDuration:0.35 animations:^{
                    [self.view layoutIfNeeded];
                    _loadingImageView.alpha = 0;
                }];
            }
           
        } else {
            if (_newy<0) {
                [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(190-64+kNavgationBar);
                }];
                //添加更新约束动画
                [UIView animateWithDuration:0.35 animations:^{
                    [self.view layoutIfNeeded];
                     _loadingImageView.alpha = 1;
                }];
            }
        }
        

        self.tableView.contentSize = CGSizeMake(0, 3*260*ScalesH);

    }
    
}

- (void)dealloc {
    NSLog(@"销毁");
}

@end
